<template>
  <div class="main order-wrapper">
    <div class="main-hd">
      <h2>{{ $t('m.fkFail') }}</h2>
    </div>
    <div class="main-hd"></div>
    <div class="content-wrap">
      <div class="form-inline" style="margin-bottom: 30px;">
        <div class="items">
          <div class="label">{{$t('m.applyTime')}}</div>
          <DatePicker v-model="time1" type="daterange" :options="disDate" format="yyyy-MM-dd" @on-change="timeChange" :placeholder="$t('m.applyTime')" class="ivu-input-w200"></DatePicker>
        </div>
        <div class="items">
          <div class="label">{{$t('m.userName')}}</div>
          <Input type="text" class="ivu-input-w200" v-model="search.userName" :placeholder="$t('m.userName')" />
        </div>
        <div class="items">
          <div class="label">{{$t('m.phone')}}</div>
          <Input type="text" class="ivu-input-w200" :placeholder="$t('m.phone')" v-model="search.phone" />
        </div>

        <div style="margin: 20px 0;">
          <Button class="search_btn" @click="emptyQueryInfo">{{$t('m.recycle')}}</Button>
          <Button class="search_btn" @click="handleFilterReset" type="primary">{{$t('m.cháxún')}}</Button>
        </div>
      </div>

      <Table border :columns="failColumns" :data="dataSource" :loading="loading" @on-selection-change="handleSelectionChange" class="table_box"></Table>
      <div style="margin-top: 5px; text-align: right;">
        <Page :total="loan_list_size" :current.sync="search.pageNumber" :page-size-opts="[10, 20, 40, 80, 100, 200, 400, 600, 800, 1000]" show-total show-elevator show-sizer @on-change="pageChange" @on-page-size-change="handleSizeChange" style="margin: 15px 0;"></Page>
      </div>
    </div>

    <!-- 添加银行卡 -->
    <Modal :loading="addLoading" :value="addModal" :title="$t('m.addBankCard')" @on-ok="addCompanyBank('formValidate')" @on-cancel="addModal = false;">
      <Form ref="formValidate" :model="addBankItem" :rules="ruleValidate" :label-width="120" style="margin-right:30px;">
        <FormItem :label="$t('m.xingming')" prop="userName">
          <Input v-model="addBankItem.userName" :placeholder="$t('m.xingming')" disabled></Input>
        </FormItem>
        <FormItem :label="$t('m.bankName')" prop="bankName">
          <Select v-model="addBankItem.bankName" :placeholder="$t('m.selectType')">
            <Option v-for="item in BankListData" :value="item.bankName">{{item.bankName}}</Option>
          </Select>
        </FormItem>        
        <FormItem :label="$t('m.cardType')" prop="accountType">
          <Select v-model="addBankItem.accountType" :placeholder="$t('m.cardType')">
            <Option :value="1">{{this.$t('m.bankCard')}}</Option>
            <Option :value="0">{{this.$t('m.brankAccount')}}</Option>
          </Select>
        </FormItem>
        <FormItem :label="$t('m.kǎhào')" prop="accountNo">
          <Input v-model="addBankItem.accountNo" :placeholder="$t('m.branchBank')"></Input>
        </FormItem>
        <FormItem :label="$t('m.openAddress')" prop="bankBranchName">
          <Input v-model="addBankItem.bankBranchName" :placeholder="$t('m.openAddress')"></Input>
        </FormItem>
      </Form>
    </Modal>

    <!-- 线下打款 -->
    <Modal :loading="makeLoading" :value="makeModal" class-name="makeModal" :title="$t('m.offlinePay')" @on-ok="makeAgainPay('makeFormValidate')" @on-cancel="makeModal = false;">
      <Form ref="makeFormValidate" :model="makeItem" :rules="makeRuleValidate" :label-width="120" style="margin-right:30px;">
        <FormItem :label="$t('m.pleaseBankCard')" prop="userBankCardId">
          <Select @on-change="onChangeBrankCard" style="width: 100%;" v-model="makeItem.userBankCardId" :placeholder="$t('m.pleaseBankCard')">
            <Option v-for="item in userBankCardList" :value="item.id" :key="item.id">{{`${item.accountName}---${item.bankName}`}}</Option>
          </Select>
        </FormItem>
        <FormItem :label="$t('m.Account')" prop="accountNo">
          <Input v-model="makeItem.accountNo" :placeholder="$t('m.qǐngshūrùzhànghào')" disabled></Input>
        </FormItem>
        <FormItem :label="$t('m.Payee')" prop="accountName">
          <Input v-model="makeItem.accountName" :placeholder="$t('m.Payee')" disabled></Input>
        </FormItem>
        <FormItem :label="$t('m.beneficiaryBank')" prop="bankName">
          <Input v-model="makeItem.bankName" :placeholder="$t('m.beneficiaryBank')" disabled></Input>
        </FormItem>
        <FormItem :label="$t('m.beneficiaryBranchBank')" prop="bankBranchName">
          <Input v-model="makeItem.bankBranchName" :placeholder="$t('m.beneficiaryBranchBank')" disabled></Input>
        </FormItem>
        <FormItem :label="$t('m.rLt')" prop="payTime">
          <DatePicker @on-change="onChangePayTime" v-model="makeItem.payTime" style="width: 100%;" type="date" :placeholder="$t('m.rLt')"></DatePicker>
        </FormItem>
        <FormItem :label="$t('m.payVoucher')" prop="imgUrl">

          <div class="demo-upload-list" v-if="makeItem.imgUrl">
            <template>
              <img :src="makeItem.imgUrl">
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click="visibleUp=true"></Icon>
                <Icon type="ios-trash-outline" @click="makeItem.imgUrl = ''"></Icon>
              </div>
            </template>
          </div>
          <Upload ref="upload" :show-upload-list="false" :format="['jpg','jpeg','png']" :before-upload="handleBeforeUpload" accept="image/jpeg, image/png" type="drag" action style="display: inline-block;width:58px;" v-if="!makeItem.imgUrl">
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
          </Upload>
          <Modal title="View Image" v-model="visibleUp">
            <img :src="makeItem.imgUrl" v-if="visibleUp" style="width: 100%">
          </Modal>

        </FormItem>
      </Form>
    </Modal>
    <!-- 重新打款 -->
    <Modal :loading="resetMakeLoading" :value="resetMakeModal" :title="$t('m.Recharge')" @on-ok="resetMakeAgainPay" @on-cancel="resetMakeModal = false;">
      <p>{{$t('m.retryPayRemark')}}</p>
    </Modal>
    <!-- 发回条数 -->
    <Modal v-model="returnModal" :title="this.$t('m.dìngdānfāhuíxiángqíngyè')" @on-ok="handleBatchWithholdOk" @on-cancel="handleBatchWithholdOk">
      <table class="table table-hover table-condensed" border>
        <!-- <thead>
        </thead>-->
        <tbody>
          <tr v-show="orderGidReturnObj.editTotalNumbers">
            <td>{{ $t('m.fāhuízǒngtiáoshù') }}</td>
            <td>{{orderGidReturnObj.editTotalNumbers}}</td>
          </tr>
          <tr v-show="orderGidReturnObj.succTotalNumbers">
            <td>{{ $t('m.fāhuíchénggōngtiáoshù') }}</td>
            <td>{{orderGidReturnObj.succTotalNumbers}}</td>
          </tr>
          <tr v-show="orderGidReturnObj.failTotalNumbers">
            <td>{{ $t('m.fāhuíshībàitiáoshù') }}</td>
            <td>{{orderGidReturnObj.failTotalNumbers}}</td>
          </tr>
        </tbody>
      </table>
    </Modal>
  </div>
</template>

<script>
import lrz from "lrz";

export default {
  data () {
    return {
      time1: [],
      disDate: {
        disabledDate (date) {
          return date && date.valueOf() > Date.now();
        }
      },
      BankListData:[],
      uploadList: [],
      visibleUp: false,
      search: {
        userName: "",
        phone: "",
        startDate: "",
        endDate: "",
        pageNumber: 1,
        pageSize: 10
      },
      //  重新打款
      resetMakeLoading: true,
      resetMakeModal: false,
      //  线下打款
      makeLoading: true,
      makeModal: false,
      row: {},
      makeItem: {
        imgUrl: "",
        payTime: null
      },
      makeRuleValidate: {
        userBankCardId: [
          {
            required: true,
            type: 'number',
            message: this.$t("m.pleaseName"),
            trigger: "change"
          }
        ],
        payTime: [
          {
            required: true,
            type: 'date',
            message: this.$t("m.rLt"),
            trigger: "change"
          }
        ],
        imgUrl: [
          {
            required: false,
            message: this.$t("m.pleaseName"),
            trigger: "blur"
          }
        ]
      },
      //  添加银行卡
      addBankItem: {
        bankName: "",
        accountType: "",
        accountNo: "",
        bankBranchName: ""
      },
      addModal: false,
      addLoading: true,
      ruleValidate: {
        accountNo: [
          {
            required: true,
            message: this.$t("m.pleaseName"),
            trigger: "blur"
          }
        ],
        bankName: [
          {
            required: true,
            message: this.$t("m.pleaseCard"),
            trigger: "blur"
          }
        ],
        accountType: [
          {
            type: "number",
            required: true,
            message: this.$t("m.qǐngxuǎnzézhuàngtài"),
            trigger: "change"
          }
        ]
      },
      returnModal: false,
      orderGidReturnObj: {},
      userBankCardList: [],
      //  列表
      loan_list_size: 1,
      dataSource: [],
      loading: false,
      failColumns: [
        {
          title: this.$t("m.applyTime"), //  申请时间
          key: "applyTime",
          width: 200,
          align: "center",
          fixed: "left"
        },
        {
          title: this.$t("m.userName"), //..姓名
          key: "userName",
          width: 200,
          align: "center",
        },
        {
          title: this.$t("m.phone"),
          key: "phone",
          width: 200,
          align: "center",
        },
        {
          title: this.$t("m.BcardN"), //..银行卡号
          key: "bankCardNo",
          width: 200,
          align: "center",
        },
        {
          title: this.$t("m.bankName"), //..银行名称
          key: "bankName",
          width: 200,
          align: "center",
        },
        {
          title: this.$t("m.loanMount"), //..借款金额
          key: "loanAmount",
          width: 200,
          align: "center",
          render: (h, param) => {
            return h("div", this.formatTreeMount(param.row.loanAmount));
          }
        },
        {
          title: this.$t("m.loanTimeLimit"), //..借款期限
          key: "loanDays",
          width: 200,
          align: "center",
        },
        {
          title: this.$t("m.rLstate"), //..打款状态
          key: "payStatus",
          width: 200,
          align: "center",
          render: (h, params) => {
            return h("div", this.$t("m.shībài"));
          }
        },
        {
          title: this.$t("m.shībàiysuányīn"), //..失败原因
          key: "failReason",
          align: "center",
          width: 200,
        },
        {
          title: this.$t("m.operate"),
          align: "center",
          width: 200,
          fixed: "right",
          className: "column-space",
          render: (h, params) => {
            const { orderGid } = params.row;

            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                    long: true
                  },
                  style: {
                    margin: "10px 0"
                  },
                  on: {
                    click: () => {
                      this.handleMakeModal(params.row);
                    }
                  }
                },
                this.$t('m.offlinePay')
              ),
              h(
                "Button",
                {
                  props: {
                    type: "success",
                    size: "small",
                    long: true
                  },
                  style: {
                    marginBottom: "10px"
                  },
                  on: {
                    click: () => {
                      this.hanleAddBank(params.row);
                    }
                  }
                },
                this.$t('m.addBankCard')
              ),
              h(
                "Button",
                {
                  props: {
                    type: "warning",
                    size: "small",
                    long: true
                  },
                  style: {
                    marginBottom: "10px"
                  },
                  on: {
                    click: () => {
                      this.handleOpenResetMakeModal(params.row);
                    }
                  }
                },
                this.$t('m.Recharge')
              ),
              h('Poptip', {
                props: {
                  confirm: true,
                  placement: "top",
                  type: 'error',
                  size: 'small',
                  long: true,
                  title: this.$t('m.Nǐquèdìngyàofāhuíma')
                },
                style: {
                  width: '100%'
                },
                on: {
                  'on-ok': () => {
                    this.detailsVisibleReturn(orderGid);
                  }
                }
              }, [
                h('Button', {
                  props: {
                    type: "error",
                    size: "small",
                    long: true
                  },
                  style: {
                    marginBottom: "10px",
                    width: '100%'
                  },
                }, this.$t("m.sendBack"))
              ]),
            ]);
          }
        }
      ]
    };
  },
  created () {
    this.getCreditOrderList();
  },
  methods: {
    onChangeBrankCard (val) {
      const filiterItem = this.userBankCardList.filter((item) => {
        return item.id === val;
      })[0];
      this.makeItem = {
        ...this.makeItem,
        ...filiterItem,
      };
    },
    detailsVisibleReturn (v) {
      this.$http
        .post("/api/laocai/order/callback", {
          orderGids: [v]
        })
        .then(res => {
          this.returnModal = true;
          if (res.body.code == 0) {
            if (res.body.result) {
              this.orderGidReturnObj = res.body.result;
            }
            this.getCreditOrderList();
          } else {
            this.$Message.warning(this.$t("m.errorCode" + res.body.code));
          }
        });
    },
    handleBatchWithholdOk () {
      this.detailsVisible = false;
      this.orderGidReturnObj = {};
    },
    emptyQueryInfo () {
      this.time1 = [];
      this.search = Object.assign(
        {},
        {
          userName: "",
          phone: "",
          startDate: "",
          endDate: "",
          pageNumber: 1
        }
      );
    },
    handleFilterReset () {
      this.$set(this.search, "pageNumber", 1);
      this.getCreditOrderList();
    },
    timeChange (e) {
      if (typeof e == "undefined") {
        this.$set(this.search, 'startDate', e[0]);
      } else if (typeof e == "object") {
        this.$set(this.search, 'startDate', e[0]);
        this.$set(this.search, 'endDate', e[1]);
      }
    },
    pageChange (e) {
      this.$set(this.search, "pageNumber", e);
      this.getCreditOrderList();
    },
    // 每页显示数量
    handleSizeChange (val) {
      this.$set(this.search, "pageSize", val);
      this.getCreditOrderList();
    },
    async getCreditOrderList () {
      this.loading = true;

      const URL =
        "/api/laocai/loan/payFail/list" + this.formatRequestStr(this.search);

      try {
        const {
          body: {
            result: { list, size },
            code
          }
        } = await this.$http.get(URL);
        this.loading = false;

        if (code === 0) {
          this.dataSource = list || [];
          this.loan_list_size = size || 1;
        }
      } catch (err) {
        this.loading = false;
      }
    },
    handleSelectionChange () { },
    //  打开线下打款
    handleMakeModal (row) {
      this.row = row;
      this.makeModal = true;
      //  调用用户银行卡列表接口
      this.getUserBankCard(row);
    },
    //
    async getUserBankCard (row) {
      const { body } = await this.$http.get(
        "/api/laocai/user/bankcard?userId=" + row.userId,
      );
      const {
        result,
        code,
      } = body;
      this.userBankCardList = result || [];
    },
    //  打开添加银行卡
    hanleAddBank (row) {
      this.queryBankList()
      this.addBankItem = row;
      this.addBankItem.bankName =''
      this.addModal = true;
    },
    queryBankList(){
      var url = `/api/laocai/loan/offLine/bankCardList`;
      this.$http.get(url).then(res => {
        if (res.data.code == 0) {          
          this.BankListData  = res.data.result
        } else {
          this.BankListData = [];
        this.$Message.success(this.$t('m.bankCard')+ this.$t('m.qǐngqiú') + this.$t("m.errorCode" + res.body.code));
        }
      });
    },
    //  打开重新打款
    handleOpenResetMakeModal (row) {
      this.row = row;
      this.resetMakeModal = true;
    },
    //  重新打款
    async resetMakeAgainPay () {
      const { orderGid } = this.row;

      const params = {
        orderGid,
      };

      const { body } = await this.$http.post(
        "/api/laocai/loan/again/pay",
        params
      );

      const { code, message } = body;
      if (code === 0) {
        this.resetMakeModal = false;

        this.getCreditOrderList();
      } else {
        this.$Message.error(message);
      }
      this.resetMakeLoading = false;
      setTimeout(() => {
        this.resetMakeLoading = true;
      }, 0);
    },
    onChangePayTime (e) {
      this.makeItem = {
        ...this.makeItem,
        payTimeStr: e,
      };
    },
    //  线下打款
    async makeAgainPay (name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          const { orderGid } = this.row;
          const { imgUrl, userBankCardId, payTimeStr } = this.makeItem;

          const params = {
            orderGid,
            userBankCardId,
            imgUrl,
            payTime: payTimeStr,
          };

          const { body } = await this.$http.post(
            "/api/laocai/loan/offLine/pay",
            params
          );

          const { code, message } = body;
          if (code === 0) {
            this.makeModal = false;
            this.$refs[name].resetFields();

            this.getCreditOrderList();
          } else {
            this.$Message.error(this.$t('m.errorCode' + code));
          }
        }
        this.makeLoading = false;
        setTimeout(() => {
          this.makeLoading = true;
        }, 0);
      });
    },
    //  添加银行卡
    async addCompanyBank (name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          const {
            bankName,
            userId,
            accountType,
            accountNo,
            bankBranchName
          } = this.addBankItem;

          const params = {
            bankName,
            userId,
            accountType,
            accountNo,
            bankBranchName
          };

          const { body } = await this.$http.post(
            "/api/laocai/user/bankCard/add",
            params
          );

          const { code, message } = body;
          if (code === 0) {
            this.addModal = false;
            this.$refs[name].resetFields();

            this.getCreditOrderList();
          } else {
            this.$Message.error(message);
          }
        } else {
          this.addLoading = false;
          setTimeout(() => {
            this.addLoading = true;
          }, 0);
        }
      });
    },
    handleBeforeUpload (file) {
      const reg = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
      const limit5 = file.size / 1024 / 1024 < 1;
      const check = this.uploadList.length < 1;

      if (!reg.test(file.type)) {
        this.$Message.error(
          this.$t("m.zhǐnéngshàngchuánjpgjpegpnggéshìdetúpiàn")
        );
        return false;
      }
      if (!limit5) {
        this.$Message.error(this.$t("m.shàngchuándetúpiànbùnéngchāoguò1MB"));
        return false;
      }
      if (!check) {
        this.$Message.error(this.$t("m.zuìduōshàngchuán1zhāngtúpiàn"));
        return false;
      }

      // 压缩图片
      lrz(file)
        .then(res => {
          const { base64, fileName } = res;
          this.makeItem.imgUrl = base64
          // console.log(base64,"你是啥啊士大夫")
        })
        .catch(err => {
          this.$Message.error(this.$t("m.yāsuōtúpiànshībài"));
        })
        .always(res => { });

      return false;
    }
  }
};
</script>

<style lang="scss" scoped>
@import "../../static/style.css";
@import "../../static/common.scss";

.order-wrapper {
  .column-space {
    padding-top: 5px;
    padding-bottom: 5px;
  }

  .search_btn {
    min-width: 100px;
    margin-right: 20px;
  }

  .operator-tools {
    margin-top: 12px;

    button {
      margin-right: 5px;
    }
  }

  .ivu-table-cell {
    padding-left: 6px;
    padding-right: 6px;
  }

  .items {
    display: inline-flex;
    width: 200px;
    flex-direction: column;
    margin-bottom: 10px;
    margin-right: 20px;
    .label {
      overflow: hidden;
      white-space: inherit;
      text-align: left;
      color: #222;
      font-size: 14px;
    }
  }
}
.makeModal {
  .priview {
    width: 100px;
    height: 100px;
    margin-bottom: 10px;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
.table_box >>> .ivu-poptip-rel {
  width: 100%;
}
.table_box >>> .ivu-poptip-confirm .ivu-poptip-body .ivu-icon {
  display: none;
}
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
